package com.meij.activity;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.SlidingPaneLayout;
import android.view.Menu;
import android.view.MenuItem;

import com.meij.R;
import com.meij.adapter.MainPagerAdapter;
import com.meij.fragment.MainFragment;

public class MainActivity extends MjActivity implements OnPageChangeListener {
	private MainPagerAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		adapter = new MainPagerAdapter(getSupportFragmentManager());
		ViewPager pager = (ViewPager) findViewById(R.id.pager);
		pager.setAdapter(adapter);
		pager.setOnPageChangeListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		menu.getItem(0).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
		case R.id.action_group:
			paneLayoutToggle();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		MainFragment mainFragment = (MainFragment) adapter.getItem(0);
		if (mainFragment.paneLayout.isOpen()) {
			mainFragment.paneLayout.closePane();
		} else {
			super.onBackPressed();
		}
	}

	private void paneLayoutToggle() {
		MainFragment mainFragment = (MainFragment) adapter.getItem(0);
		SlidingPaneLayout paneLayout = mainFragment.paneLayout;
		if (paneLayout == null) {
			return;
		}
		if (paneLayout.isOpen()) {
			paneLayout.closePane();
		} else {
			paneLayout.openPane();
		}
	}

	@Override
	public void onPageSelected(int arg0) {
		MainFragment mainFragment = (MainFragment) adapter.getItem(0);
		if (mainFragment.paneLayout == null) {
			return;
		}
		mainFragment.paneLayout.closePane();
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	@Override
	public void onPageScrollStateChanged(int arg0) {

	}

}
